package middleware

import (
	"github.com/gin-gonic/gin"
	"go-caipu/pkg/setting"
	"gorm.io/gorm/utils"
	"net/http"
	"net/url"
)

func CORSMiddleware(cfg *setting.Cfg) gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method

		origin := c.Request.Header.Get("Origin")
		if origin == "" {
			// 尝试使用Referer
			referer := c.Request.Header.Get("Referer")
			if referer != "" {
				// 从Referer中提取源
				if u, err := url.Parse(referer); err == nil {
					// 构建源：协议+主机（包括端口，如果非默认）
					origin = u.Scheme + "://" + u.Host
				}
			}
		}

		//允许访问所有域
		if cfg.Application.Mode != "development" {
			allow := cfg.Application.AllowedOrigins
			if len(allow) > 0 && utils.Contains(allow, origin) {
				c.Header("Access-Control-Allow-Origin", origin) // 关键：设置为通过验证的具体源
			} else {
				c.JSON(401, gin.H{"origin": origin, "code": 401, "msg": "origin未在授权范围内"})
				c.Abort()
				return
			}

		} else {
			c.Header("Access-Control-Allow-Origin", c.GetHeader("Origin"))
		}
		c.Header("Access-Control-Allow-Credentials", "true")

		if method == "OPTIONS" {
			c.Header("Access-Control-Allow-Methods", c.GetHeader("Access-Control-Request-Method"))
			c.Header("Access-Control-Allow-Headers", c.GetHeader("Access-Control-Request-Headers"))
			c.Header("Access-Control-Max-Age", "7200")
			c.AbortWithStatus(http.StatusNoContent)
			return
		}
		c.Next()
	}
}
